# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
from coin.base.datetime_util import to_datetime, to_timestamp_int


def _get_next_split(ts, mins_after_midnight=0):
  dt = to_datetime(ts)
  dt_midnight = to_datetime(dt.date())
  assert dt >= dt_midnight
  return dt_midnight + datetime.timedelta(days=1, minutes=mins_after_midnight)


def split_time_range(from_ts, to_ts, split_mins_after_midnight=0):
  from_dt = to_datetime(from_ts)
  to_dt = to_datetime(to_ts)
  assert from_dt < to_dt

  ranges = []

  while True:
    next_split_dt = _get_next_split(from_dt, mins_after_midnight=split_mins_after_midnight)
    if next_split_dt >= to_dt:
      ranges.append(
          (to_datetime(from_dt).date(), to_timestamp_int(from_dt), to_timestamp_int(to_dt)))
      break
    ranges.append(
        (to_datetime(from_dt).date(), to_timestamp_int(from_dt), to_timestamp_int(next_split_dt)))
    from_dt = next_split_dt

  return ranges


def get_okex_huobi_futures_product_expiry_str(sub_req, product):
  if (sub_req.market_type == 'Futures' and sub_req.exchange in ['Huobi', 'Okex']):
    if product.contract_type in ['this_week', 'current_week']:
      return 'this_week'
    elif product.contract_type == 'next_week':
      return 'next_week'
    elif product.contract_type in ['quarter', 'current_quarter']:
      return 'quarter'
    elif product.contract_type == 'next_quarter':
      return 'next_quarter'
    elif product.contract_type == 'perpetual':
      return None
    else:
      raise ValueError(sub_req, product)
  else:
    return None
